<template>
  <a-modal wrapClassName="moadlWrap" width="80%" :visible="show" :confirm-loading="confirmLoading" @cancel="cancel">
    <template slot="title">
      JSON配置器
      <EchoConfig @refreshKey="refreshListKey" />
    </template>
    <a-tabs default-active-key="1" force-render>
      <a-tab-pane key="1" tab="基本信息">
        <BasePane ref="basePaneRef" type="base" :tabsList="baseList"></BasePane>
      </a-tab-pane>
      <!-- <a-tab-pane key="2" tab="人员信息">
        <BasePane type="person" :tabsList="personList"></BasePane>
      </a-tab-pane> -->
      <!-- <a-tab-pane key="3" tab="厂区信息">
        <div class="moadlWrap_button">
          <div class="moadlWrap_button">
            <span>自动回显：</span>
            <a-switch
              v-model="$store.state.formJson.formObj['FACTORY'].auto"
              checked-children="开"
              un-checked-children="关"
            />
          </div>
          <a-popconfirm title="确认重置该项配置？" ok-text="确认" cancel-text="取消" @confirm="reset('FACTORY')">
            <a-button type="danger">重置</a-button>
          </a-popconfirm>
        </div>
        <FactoryPane></FactoryPane>
      </a-tab-pane> -->
      <a-tab-pane key="4" tab="通用模态框">
        <div class="moadlWrap_button">
          <div class="moadlWrap_button">
            <span>自动回显：</span>
            <a-switch
              v-model="$store.state.formJson.formObj['GENERAL'].auto"
              checked-children="开"
              un-checked-children="关"
            />
          </div>
          <a-popconfirm title="确认重置该项配置？" ok-text="确认" cancel-text="取消" @confirm="reset('GENERAL')">
            <a-button type="danger">重置</a-button>
          </a-popconfirm>
        </div>
        <GeneralPane></GeneralPane>
      </a-tab-pane>
      <a-tab-pane key="5" tab="列表模态框">
        <ListPane :key="listKey"></ListPane>
      </a-tab-pane>
      <!-- <a-tab-pane key="6" tab="下拉模态框">
        <BasePane type="DROP" :tabsList="dropList"></BasePane>
      </a-tab-pane> -->
      <a-tab-pane key="7" tab="自定义模态框">
        <CustomPane></CustomPane>
      </a-tab-pane>
    </a-tabs>
    <div slot="footer">
      <a-button type="primary" @click="showJson">预览json</a-button>
      <a-button type="primary" @click="confirm">确认</a-button>
      <a-button type="info" @click="cancel">取消</a-button>
    </div>
    <ShowJson ref="showJsonRef"></ShowJson>
  </a-modal>
</template>

<script>
import { factoryFields } from '@/views/businessAssembly/jsonComponent/constant/factoryFields.js'

export default {
  data() {
    return {
      listKey: 0, // 列表key值
      database: 'YJENT', // 数据库名
      show: false, // 组件的显示与隐藏
      confirmLoading: false, // 确认按钮的加载状态
      tabsList: [
        {
          id: '1',
          label: '基本信息',
          type: 'base'
        },
        {
          id: '2',
          label: '人员信息',
          type: 'person'
        }
      ], // 标签列表
      baseList: [
        {
          id: '1',
          name: '企业信息',
          typeSecond: 'ent'
        },
        {
          id: '2',
          name: '联系人信息',
          typeSecond: 'link'
        },
        {
          id: '3',
          name: '邮寄信息',
          typeSecond: 'send'
        }
      ], // 基本信息列表
      personList: [
        {
          id: '1',
          name: '法人',
          typeSecond: 'LEGAL'
        },
        {
          id: '2',
          name: '企业负责人',
          typeSecond: 'ENTMGR'
        },
        {
          id: '3',
          name: '生产负责人',
          typeSecond: 'WORKMGR'
        },
        {
          id: '4',
          name: '质量负责人',
          typeSecond: 'QUAMGR'
        },
        {
          id: '5',
          name: '技术负责人',
          typeSecond: 'TECMGR'
        },
        {
          id: '6',
          name: '管理者代表',
          typeSecond: 'REPMGR'
        },
        {
          id: '7',
          name: '机构负责人',
          typeSecond: 'Apl_per_drope_quamgrorg'
        },
        {
          id: '8',
          name: '西药审方员',
          typeSecond: 'Apl_per_drope_enmedexam'
        },
        {
          id: '9',
          name: '中药审方员',
          typeSecond: 'Apl_per_drope_cnmedexam'
        }
      ], // 配置人员列表
      dropList: [
        {
          id: '1',
          name: '生产范围',
          typeSecond: 'PRODSCOPE'
        },
        {
          id: '2',
          name: '器械生产品种',
          typeSecond: 'std_eqPro_catelc'
        },
        {
          id: '3',
          name: '器械生产范围',
          typeSecond: 'std_eqPro_scope'
        },
        {
          id: '4',
          name: '器械经营范围',
          typeSecond: 'std_eqPro_opeScope'
        },
        {
          id: '5',
          name: '药品批发经营范围',
          typeSecond: 'std_drOpe_wholesaleScope'
        },
        {
          id: '6',
          name: '药品零售经营范围',
          typeSecond: 'std_drOpe_retailScope'
        },
        {
          id: '7',
          name: '药品零售/批发经营范围',
          typeSecond: 'std_drOpe_whoAndretasaleScope'
        },
        {
          id: '8',
          name: '化妆品产品单元',
          typeSecond: 'std_copro_unit'
        },
        {
          id: '9',
          name: '拟受理单位',
          typeSecond: 'PREACCE'
        },
        {
          id: '10',
          name: '地图',
          typeSecond: 'MAP'
        },
        {
          id: '11',
          name: '药品生产分类码',
          typeSecond: 'DRPROTYPE'
        }
      ], // 下拉模态框列表
      databaseList: [], // 数据库表列表
      jsonData: {} // json数据
    }
  },
  components: {
    BasePane: () => import('@/views/businessAssembly/jsonComponent/basePane.vue'),
    PersonPane: () => import('@/views/businessAssembly/jsonComponent/personPane.vue'),
    FactoryPane: () => import('@/views/businessAssembly/jsonComponent/factoryPane.vue'),
    ShowJson: () => import('@/views/businessAssembly/public/spareparts/showJson.vue'),
    GeneralPane: () => import('@/views/businessAssembly/jsonComponent/generalPane.vue'),
    ListPane: () => import('@/views/businessAssembly/jsonComponent/listPane.vue'),
    CustomPane: () => import('@/views/businessAssembly/jsonComponent/customPane.vue'),
    EchoConfig: () => import('@/views/businessAssembly/jsonComponent/base/echoConfig.vue')
  },
  mounted() {
    this.dropList.forEach(v => {
      if (!(v.typeSecond in this.$store.state.formJson.formObj.DROP)) {
        let obj = {
          attrForm: {
            title: v.name,
            type: 'single',
            table: '',
            ismultiple: 'false',
            filter: {},
            fiterList: []
          },
          filedList: [],
          auto: false
        }
        this.$set(this.$store.state.formJson.formObj.DROP, v.typeSecond, obj)
      }
    })
    this.personList.forEach(v => {
      if (!(v.typeSecond in this.$store.state.formJson.formObj.person)) {
        let obj = {
          attrForm: {
            apltable: v.typeSecond,
            title: v.name,
            table: '',
            yjctable: '',
            type: 'single',
            autoacho: 'true',
            params: {},
            paramsList: [],
            filter: {},
            fiterList: []
          },
          filedList: [],
          auto: false
        }
        this.$set(this.$store.state.formJson.formObj.person, v.typeSecond, obj)
      }
    })
  },
  methods: {
    // 初始化
    init() {
      this.$store.dispatch('GETTABLES')
      // this.$store.dispatch('GET_YJLIC_TABLESY')
      this.show = true
    },
    // 重置
    reset(type) {
      if (type == 'FACTORY') {
        let arry = []
        for (let key in factoryFields) {
          arry.push({
            b: key,
            mapping: '',
            hidden: 'false',
            describe: factoryFields[key]
          })
        }
        this.$store.state.formJson.formObj[type] = {
          attrForm: {
            title: '厂区信息',
            type: 'single'
          },
          filedList: arry,
          auto: false
        }
      } else if (type == 'GENERAL') {
        this.$store.state.formJson.formObj[type] = {
          attrForm: {
            apltable: '',
            title: '通用模态框',
            type: 'multiple',
            isprodname: 'false'
          },
          filedList: [],
          auto: false
        }
      }
    },
    // 刷新列表模态框的key
    refreshListKey() {
      this.listKey++
    },
    // 预览json
    showJson() {
      this.handleJson()
      this.$refs.showJsonRef.init(this.jsonData)
    },
    // 填写的数据转换为json
    handleJson() {
      // 定义用来存放数据得全局对象
      let globalObj = {}
      globalObj.autoload = []
      globalObj.autoloadlist = []
      // vuex数据对象
      let obj = JSON.parse(JSON.stringify(this.$store.state.formJson.formObj))
      // 遍历对象两次取得最底层数据
      for (let keyFirst in obj) {
        if (keyFirst == 'FACTORY' || keyFirst == 'GENERAL') {
          this.handleBase(obj[keyFirst], keyFirst, null, globalObj)
        } else if (
          keyFirst == 'base' ||
          keyFirst == 'person' ||
          keyFirst == 'LIST' ||
          keyFirst == 'DROP' ||
          keyFirst == 'CUSTOM'
        ) {
          for (let keySecond in obj[keyFirst]) {
            this.handleBase(obj[keyFirst][keySecond], keyFirst, keySecond, globalObj)
          }
        }
      }
      this.jsonData = globalObj
    },
    // 处理json底层数据
    handleBase(obj, keyFirst, keySecond, globalObj) {
      let attrFormCopy = JSON.parse(JSON.stringify(obj.attrForm))
      if (keyFirst == 'base' || keyFirst == 'person' || keyFirst == 'CUSTOM') {
        attrFormCopy.autoacho = attrFormCopy.autoacho == 'true' ? true : false
        delete attrFormCopy.ismultiple
        delete attrFormCopy.ischoice
        delete attrFormCopy.isaddbtn
        delete attrFormCopy.lookname
        if (keyFirst == 'person') {
          attrFormCopy.emptybtn = attrFormCopy.emptybtn == 'true' ? true : false
        }
      } else if (keyFirst == 'LIST') {
        attrFormCopy.ischoice = attrFormCopy.ischoice == 'true' ? true : false
        attrFormCopy.isaddbtn = attrFormCopy.isaddbtn == 'true' ? true : false
        if (attrFormCopy.type == 'multiple') {
          delete attrFormCopy.lookname
          delete attrFormCopy.tname
        }
        if (attrFormCopy.ischoice) {
          attrFormCopy.ismultiple = attrFormCopy.ismultiple == 'true' ? true : false
        } else {
          delete attrFormCopy.ismultiple
        }
      } else if (keyFirst == 'DROP') {
        attrFormCopy.ismultiple = attrFormCopy.ismultiple == 'true' ? true : false
        attrFormCopy.isfaname = attrFormCopy.isfaname == 'true' ? true : false
        attrFormCopy.isaddonly = attrFormCopy.isaddonly == 'true' ? true : false
        attrFormCopy.isreduceonly = attrFormCopy.isreduceonly == 'true' ? true : false
        delete attrFormCopy.apltable
        delete attrFormCopy.table
        delete attrFormCopy.yjctable
        delete attrFormCopy.lookname
        delete attrFormCopy.ischoice
        delete attrFormCopy.isaddbtn
      } else if (keyFirst == 'GENERAL') {
        attrFormCopy.isprodname = attrFormCopy.isprodname == 'true' ? true : false
      }
      // 判断是否选择了申请表和企业表
      if (
        (attrFormCopy.apltable && attrFormCopy.table && keyFirst != 'DROP') ||
        keyFirst == 'FACTORY' ||
        keyFirst == 'DROP' ||
        (keyFirst == 'GENERAL' && attrFormCopy.apltable) ||
        (keyFirst == 'LIST' && (attrFormCopy.apltable || attrFormCopy.yjctable))
      ) {
        if (keyFirst == 'CUSTOM') {
          console.log('keyFirst', keyFirst)
        }
        // 处理查询条件
        if (attrFormCopy?.paramsList?.length) {
          attrFormCopy.paramsList.forEach(v => {
            attrFormCopy.params[v.field] = v.value
          })
        }
        // 处理过滤条件
        if (attrFormCopy?.fiterList?.length) {
          attrFormCopy.fiterList.forEach(v => {
            attrFormCopy.filter[v.field] = v.value
          })
        }
        // mapping列表
        let tempList = JSON.parse(JSON.stringify(obj.filedList))
        let mapping = []
        let maprelation = {}
        let rules = {}
        if (attrFormCopy.lookname && attrFormCopy.tname) {
          mapping.push({
            b: '$lookname',
            t: attrFormCopy.tname,
            hidden: true,
            describe: `${attrFormCopy.lookname}字段逗号分隔的自定义回显值`
          })
          delete attrFormCopy.tname
        }

        if (keyFirst == 'FACTORY' || keyFirst == 'GENERAL') {
          tempList.forEach(item => {
            if (item.mapping) {
              mapping.push({
                b: item.b,
                t: item.mapping,
                describe: item.describe,
                hidden: item.hidden == 'true' ? true : false
              })
            }
          })
        } else if (keyFirst == 'LIST') {
          if (tempList?.length) {
            tempList.forEach(v => {
              if (v.b) {
                maprelation[v.b] = v.t
              }
              if (v.rules.length && v.mapping) {
                rules[v.t] = v.rules
              }
              if (v.mapping) {
                let tempObj = {
                  b: v.t,
                  t: v.mapping,
                  describe: v.describe,
                  hidden: v.hidden == 'true' ? true : false,
                  isparam: v.isparam == 'true' ? true : false,
                  sort: v.sort,
                  type: v.type,
                  options: v.options,
                  expression: v.expression
                }
                mapping.push(tempObj)
              }
            })
            mapping.sort((a, b) => {
              return a.sort - b.sort
            })
          }
        } else if (keyFirst == 'DROP') {
          if (tempList.length) {
            tempList.forEach(item => {
              if (item.mapping) {
                let obj = {}
                if (item.isparam != undefined) {
                  obj = {
                    b: item.b,
                    t: item.mapping,
                    describe: item.describe,
                    isparam: item.isparam
                  }
                } else {
                  obj = {
                    b: item.b,
                    t: item.mapping,
                    describe: item.describe
                  }
                }
                mapping.push(obj)
              }
            })
          }
        } else {
          if (tempList?.length) {
            tempList.forEach(v => {
              if (v.b) {
                maprelation[v.b] = v.t
              }
              if (v.rules.length && v.mapping) {
                rules[v.t] = v.rules
              }
              if (v.mapping) {
                let tempObj = {
                  b: v.t,
                  t: v.mapping,
                  describe: v.describe,
                  hidden: v.hidden == 'true' ? true : false,
                  type: v.type,
                  sort: v.sort,
                  options: v.options,
                  expression: v.expression
                }
                mapping.push(tempObj)
              }
            })
            mapping.sort((a, b) => {
              return a.sort - b.sort
            })
          }
        }
        // 处理全局的对象的键值
        let globalKey = ''
        if (keyFirst == 'person' || keyFirst == 'LIST' || keyFirst == 'DROP' || keyFirst == 'CUSTOM') {
          globalKey = keySecond
        } else if (keyFirst == 'base') {
          globalKey = attrFormCopy.table.toUpperCase()
        } else if (keyFirst == 'FACTORY' || keyFirst == 'GENERAL') {
          globalKey = keyFirst
        }
        if (JSON.stringify(attrFormCopy.params) == '{}') {
          delete attrFormCopy.params
        }
        if (JSON.stringify(attrFormCopy.filter) == '{}') {
          delete attrFormCopy.filter
        }
        delete attrFormCopy.paramsList
        delete attrFormCopy.fiterList
        // 是否自动回显
        if (obj.auto) {
          if (keyFirst == 'LIST') {
            globalObj.autoloadlist.push(globalKey)
          } else {
            globalObj.autoload.push(globalKey)
          }
        }
        if (keyFirst == 'FACTORY' && mapping.length == 0) {
          return
        }
        if (keyFirst == 'DROP' && mapping.length == 0) {
          return
        }

        // 数据拼装
        globalObj[globalKey] = {
          ...attrFormCopy
        }
        if (JSON.stringify(mapping) != '{}') {
          globalObj[globalKey].mapping = mapping
        }
        if (JSON.stringify(maprelation) != '{}') {
          globalObj[globalKey].maprelation = maprelation
        }
        if (JSON.stringify(rules) != '{}') {
          globalObj[globalKey].rules = rules
        }
      }
    },
    // 确认
    confirm() {
      this.handleJson()
      this.$store.commit('setHandleObj', this.jsonData)
      this.$message.success('保存成功!')
      this.show = false
    },
    // 取消
    cancel() {
      this.show = false
    }
  }
}
</script>

<style lang="less" scoped>
.moadlWrap_button {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.moadlWrap_button_left {
  display: flex;
  align-items: center;
}
</style>
